package service

import (
	"context"
	"fmt"

	"gitee.com/wangshh_123/cross-pay-go/src/models"
	"gorm.io/gorm"
)

type ExchangeLossRuleService struct {
	db *gorm.DB
}

func NewExchangeLossRuleService(db *gorm.DB) *ExchangeLossRuleService {
	return &ExchangeLossRuleService{db: db}
}

// GetExchangeLossRule 获取用户专属或全局默认汇率损失规则
func (s *ExchangeLossRuleService) GetExchangeLossRule(ctx context.Context, userID *int64) (*models.ExchangeLossRule, error) {
	var rule models.ExchangeLossRule

	// 优先查用户专属
	if userID != nil {
		err := s.db.WithContext(ctx).
			Where("user_id = ? AND status = ?", *userID, "active").
			First(&rule).Error
		if err == nil {
			return &rule, nil
		}
	}

	// 查全局默认
	err := s.db.WithContext(ctx).
		Where("user_id IS NULL AND is_default = 1 AND status = ?", "active").
		First(&rule).Error
	if err != nil {
		return nil, fmt.Errorf("未找到汇率损失规则")
	}
	return &rule, nil
}

// CreateExchangeLossRule 新增
func (s *ExchangeLossRuleService) CreateExchangeLossRule(ctx context.Context, rule *models.ExchangeLossRule) error {
	return s.db.WithContext(ctx).Create(rule).Error
}

// UpdateExchangeLossRule 更新
func (s *ExchangeLossRuleService) UpdateExchangeLossRule(ctx context.Context, id int64, update map[string]interface{}) error {
	return s.db.WithContext(ctx).Model(&models.ExchangeLossRule{}).Where("id = ?", id).Updates(update).Error
}

// DeleteExchangeLossRule 删除
func (s *ExchangeLossRuleService) DeleteExchangeLossRule(ctx context.Context, id int64) error {
	return s.db.WithContext(ctx).Delete(&models.ExchangeLossRule{}, id).Error
}

// GetExchangeLossRuleByID 查询单条
func (s *ExchangeLossRuleService) GetExchangeLossRuleByID(ctx context.Context, id int64) (*models.ExchangeLossRule, error) {
	var rule models.ExchangeLossRule
	err := s.db.WithContext(ctx).First(&rule, id).Error
	if err != nil {
		return nil, err
	}
	return &rule, nil
}
